#!/bin/bash
set -euo pipefail

# 清理外部注入的 RUSTFLAGS，避免遗留参数影响交叉链接
unset RUSTFLAGS

export TREE_INSTALL_HNP_PATH="${HNP_PUBLIC_PATH}/zoxide.org/zoxide_1.0.0"

sys_prefix=${PREFIX-}
export PREFIX="${TREE_INSTALL_HNP_PATH}"
echo "${PREFIX}"

TARGET_TRIPLE="${TARGET_PLATFORM:-aarch64-linux-ohos}"
FALLBACK_TRIPLE="aarch64-unknown-linux-musl"
CARGO_BIN=${CARGO:-cargo}
RUSTUP_LLD_BIN=${RUSTUP_RUST_LLD:-"$HOME/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/bin/rust-lld"}

export CARGO_REGISTRIES_CRATES_IO_PROTOCOL="sparse"
export CARGO_REGISTRIES_CRATES_IO_INDEX="${CARGO_REGISTRIES_CRATES_IO_INDEX:-https://mirrors.ustc.edu.cn/crates.io-index/}"

ensure_rust_target() {
    local target="$1"
    if ! rustc --print target-list | grep -q "^${target}\$"; then
        return 1
    fi
    if ! rustup target list --installed | grep -q "^${target}\$"; then
        echo "Info: 自动安装 Rust 目标 ${target}"
        rustup target add "${target}"
    fi
    return 0
}

if ! ensure_rust_target "${TARGET_TRIPLE}"; then
    if ensure_rust_target "${FALLBACK_TRIPLE}"; then
        echo "Warn: 当前 Rust 不支持 ${TARGET_TRIPLE}，自动回退到 ${FALLBACK_TRIPLE}"
        TARGET_TRIPLE="${FALLBACK_TRIPLE}"
    else
        echo "Error: rustc 无法使用 ${TARGET_TRIPLE} 或回退目标 ${FALLBACK_TRIPLE}"
        exit 4
    fi
fi

SYSROOT_PATH="${SYSROOT:-${OHOS_SDK}/native/sysroot}"
USE_SYSROOT_FLAG="true"
TRIPLE_ENV=$(echo "${TARGET_TRIPLE}" | tr '[:lower:]-' '[:upper:]_')
OHOS_CRT_DIR="${SYSROOT_PATH}/usr/lib/aarch64-linux-ohos"

PREFERRED_LINKER="${COMPILER_TOOLCHAIN}aarch64-linux-ohos-clang"
if [[ "${TARGET_TRIPLE}" == *"linux-musl"* ]]; then
    if [[ -x "${RUSTUP_LLD_BIN}" ]]; then
        PREFERRED_LINKER="${RUSTUP_LLD_BIN}"
    else
        PREFERRED_LINKER="rust-lld"
    fi
    USE_SYSROOT_FLAG="false"
fi

if [[ "${TARGET_TRIPLE}" == *"ohos"* ]]; then
    missing_crt=false
    for crt in Scrt1.o crti.o crtbeginS.o crtendS.o crtn.o; do
        if [ ! -f "${OHOS_CRT_DIR}/${crt}" ]; then
            missing_crt=true
            break
        fi
    done

    if ${missing_crt}; then
        echo "Warn: OHOS sysroot 缺少必要 CRT 文件，回退到 ${FALLBACK_TRIPLE}"
        TARGET_TRIPLE="${FALLBACK_TRIPLE}"
        TRIPLE_ENV=$(echo "${TARGET_TRIPLE}" | tr '[:lower:]-' '[:upper:]_')
        USE_SYSROOT_FLAG="false"
        if [[ -x "${RUSTUP_LLD_BIN}" ]]; then
            PREFERRED_LINKER="${RUSTUP_LLD_BIN}"
        else
            PREFERRED_LINKER="rust-lld"
        fi
    fi
fi

if [ "${PREFERRED_LINKER}" != "rust-lld" ] && [ ! -x "${PREFERRED_LINKER}" ]; then
    echo "Warn: ${PREFERRED_LINKER} 不存在，使用默认 clang"
    PREFERRED_LINKER="${COMPILER_TOOLCHAIN}clang"
fi

SYSROOT_FLAG=""
FUSE_LD_FLAG="-Clink-arg=-fuse-ld=${LD}"
if [[ "${PREFERRED_LINKER}" == *"rust-lld"* ]]; then
    FUSE_LD_FLAG=""
fi

RUSTFLAGS_LIST=()
if [[ "${USE_SYSROOT_FLAG}" == "true" ]]; then
    RUSTFLAGS_LIST+=("-Clink-arg=--sysroot=${SYSROOT_PATH}")
fi
if [[ -n "${FUSE_LD_FLAG}" ]]; then
    RUSTFLAGS_LIST+=("${FUSE_LD_FLAG}")
fi
eval "export CARGO_TARGET_${TRIPLE_ENV}_LINKER=\"${PREFERRED_LINKER}\""
eval "export CARGO_TARGET_${TRIPLE_ENV}_RUSTFLAGS=\"${RUSTFLAGS_LIST[*]}\""

"${CARGO_BIN}" build --release --target "${TARGET_TRIPLE}"

BUILD_OUTPUT="target/${TARGET_TRIPLE}/release/zoxide"
if [ ! -f "${BUILD_OUTPUT}" ]; then
    echo "Error: ${BUILD_OUTPUT} not found"
    exit 3
fi

INSTALL_ROOT="${TREE_INSTALL_HNP_PATH}"
BIN_DIR="${INSTALL_ROOT}/usr/bin"
MAN_DIR="${INSTALL_ROOT}/usr/share/man/man1"
DOC_DIR="${INSTALL_ROOT}/usr/share/doc/zoxide"
COMPLETION_DIR="${INSTALL_ROOT}/usr/share/zoxide/completions"

mkdir -p "${BIN_DIR}" "${MAN_DIR}" "${DOC_DIR}" "${COMPLETION_DIR}"
install -m 755 "${BUILD_OUTPUT}" "${BIN_DIR}/zoxide"
install -m 644 man/man1/*.1 "${MAN_DIR}/"
install -m 644 README.md CHANGELOG.md LICENSE "${DOC_DIR}/"
cp contrib/completions/* "${COMPLETION_DIR}/"

cp hnp.json "${INSTALL_ROOT}/"
pushd "${INSTALL_ROOT}/../"
    ${HNP_TOOL} pack -i "${INSTALL_ROOT}" -o "${ARCHIVE_PATH}/"
    tar -zvcf "${ARCHIVE_PATH}/ohos_zoxide_1.0.0.tar.gz" zoxide_1.0.0/
popd

export PREFIX="${sys_prefix}"